package com.ashley.phonemsn

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import java.lang.Thread.UncaughtExceptionHandler
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Call
import androidx.compose.material.icons.filled.Email
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.ComposeView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.ashley.phonemsn.ui.theme.PhoneMSNTheme

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"
    private lateinit var callFragment: CallFragment
    private lateinit var smsFragment: SmsFragment
    private lateinit var contactsFragment: ContactFragment
    private var currentTab by mutableStateOf(Tab.CALL)

    enum class Tab {
        CALL, SMS
    }
    
    private val requestCallPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) {
        isGranted ->
        if (isGranted) {
            Toast.makeText(this, "电话权限已获取", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "电话权限被拒绝，将无法拨打电话", Toast.LENGTH_SHORT).show()
        }
    }

    private val requestSmsPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) {
        isGranted ->
        if (isGranted) {
            Toast.makeText(this, "短信权限已获取", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "短信权限被拒绝，将无法发送短信", Toast.LENGTH_SHORT).show()
        }
    }
    
    private val requestContactsPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) {
        isGranted ->
        if (isGranted) {
            Toast.makeText(this, "联系人权限已获取", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "联系人权限被拒绝，将无法访问通讯录", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        // 设置全局异常处理器捕获系统级错误
        setupGlobalExceptionHandler()
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 初始化Fragment
        callFragment = CallFragment()
        smsFragment = SmsFragment()
        contactsFragment = ContactFragment()
        
        // 设置联系人选择回调
        contactsFragment.setOnContactSelectedListener {
            // 将选择的联系人电话号码传递给当前选中的Fragment
            when (currentTab) {
                Tab.CALL -> callFragment.onContactSelected(it.phoneNumber)
                Tab.SMS -> smsFragment.onContactSelected(it.phoneNumber)
            }
        }
        
        // 检查并请求权限
        checkPermissions()

        // 初始显示CallFragment
        replaceFragment(callFragment)

        // 设置Compose底部导航
        val composeView = findViewById<ComposeView>(R.id.compose_navigation)
        composeView.setContent {
            PhoneMSNTheme {
                NavigationBar {
                    NavigationBarItem(
                        selected = currentTab == Tab.CALL,
                        onClick = { 
                            currentTab = Tab.CALL
                            replaceFragment(callFragment)
                        },
                        icon = { Icon(Icons.Default.Call, contentDescription = "电话") },
                        label = { Text("电话") }
                    )
                    NavigationBarItem(
                        selected = currentTab == Tab.SMS,
                        onClick = { 
                            currentTab = Tab.SMS
                            replaceFragment(smsFragment)
                        },
                        icon = { Icon(Icons.Default.Email, contentDescription = "短信") },
                        label = { Text("短信") }
                    )
                }
            }
        }
    }

    private fun setupGlobalExceptionHandler() {
        val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
        
        Thread.setDefaultUncaughtExceptionHandler(object : UncaughtExceptionHandler {
            override fun uncaughtException(thread: Thread, ex: Throwable) {
                // 检查是否是三星游戏管理器相关的错误
                if (ex is IllegalStateException && 
                    ex.message?.contains("gamemanager system service is not available") == true) {
                    // 记录错误但不崩溃应用
                    Log.e(TAG, "捕获到三星游戏管理器系统服务错误，这是设备问题而非应用问题", ex)
                    // 继续正常执行，不抛出异常
                    return
                }
                
                // 其他异常交给默认处理器处理
                defaultHandler?.uncaughtException(thread, ex)
            }
        })
    }

    private fun replaceFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .commit()
    }
    
    private fun checkPermissions() {
        // 检查电话权限
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.CALL_PHONE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestCallPermissionLauncher.launch(Manifest.permission.CALL_PHONE)
        }

        // 检查短信权限
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.SEND_SMS
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestSmsPermissionLauncher.launch(Manifest.permission.SEND_SMS)
        }
        
        // 检查联系人权限
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_CONTACTS
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestContactsPermissionLauncher.launch(Manifest.permission.READ_CONTACTS)
        }
    }
    
    // 切换到通讯录标签页的方法
    fun switchToContactsTab() {
        replaceFragment(contactsFragment)
    }
}